<template>
  <el-upload ref="uploadFile" :before-remove="beforeRemove" v-on="$listeners" v-bind="$attrs" :file-list="fileList" class="upload-demo" action="#" :auto-upload="false" :on-remove="removeFile" :on-change="fileChange" :limit="max" :on-exceed="handleExceed">
    <el-button size="small"  :type="fileLength === max ? 'info' : 'primary'" @click="stopUpload">{{uploadText}}</el-button>
    <div slot="tip" class="el-upload__tip">{{tips}}</div>
  </el-upload>
</template>
<script>
export default {
  name: "XiaobuUploadFile",
  props: {
    tips: {
      type: String,
      default: "请上传文件"
    },
    uploadText: {
      type: String,
      default: "点击上传"
    },
    max: {
      type: Number,
      default: 3
    },
    fileList: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  watch: {
    fileList(val) {
      this.fileLength = val.length
    }
  },
  data() {
    return {
      fileLength: 0
    }
  },
  created() {
    this.$nextTick(() => {
      this.fileLength = this.$refs.uploadFile.uploadFiles.length
    })
  },
  methods: {
    /**
     * @description: 文件个数更改
     * @param {*}
     * @return {*}
     * @author: syx
     */
    fileChange(file, fileList) {
      const accept = this.$attrs.accept || ""
      if (accept) {
        const fileArr = file.name.split(".")
        const fileType = "." + fileArr[fileArr.length - 1]
        const acceptFileTypeArr = accept.split(",")
        if (!acceptFileTypeArr.includes(fileType)) {
          this.$message.warning("请上传支持的文件类型")
          fileList.pop()
          return
        }
      }
      this.$nextTick(() => {
        this.fileLength = this.$refs.uploadFile.uploadFiles.length
        this.$emit("uploadSuccess", this.$refs.uploadFile.uploadFiles)
      })
    },
    /**
     * @description: 移除文件
     * @param {*}
     * @return {*}
     * @author: syx
     */
    removeFile(val){
      this.$nextTick(() => {
        this.fileLength = this.$refs.uploadFile.uploadFiles.length
        this.$emit("remove", val)
      })
    },
    /**
     * @description: 数量够了 禁止下载
     * @param {*}
     * @return {*}
     * @author: syx
     */
    stopUpload() {
      if (this.max === this.fileLength) {
        //阻止冒泡
        if (event.stopPropagation) { 
          // 针对 Mozilla 和 Opera 
          event.stopPropagation()
        } else if (window.event) { 
          // 针对 IE 
          window.event.cancelBubble = true
        }
      }
    },
    /**
     * @description: 获取文件列表
     * @param {*}
     * @return {*}
     * @author: syx
     */  
    getFileList(){
      return this.$refs.uploadFile.uploadFiles
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 ${this.max} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`)
    }
  }
}
</script>

